home *** CD-ROM | disk | FTP | other *** search
/ Java Developer's Companion / Java Developer's Companion.iso / documentation / tutorial / applet / communication / example / TalkClientApplet.java < prev    next >
Encoding:
Java Source  |  1997-07-13  |  9.8 KB  |  305 lines

  1. /*
  2.  * Copyright (c) 1995-1997 Sun Microsystems, Inc. All Rights Reserved.
  3.  *
  4.  * Permission to use, copy, modify, and distribute this software
  5.  * and its documentation for NON-COMMERCIAL purposes and without
  6.  * fee is hereby granted provided that this copyright notice
  7.  * appears in all copies. Please refer to the file "copyright.html"
  8.  * for further important copyright and licensing information.
  9.  *
  10.  * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
  11.  * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  12.  * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  13.  * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
  14.  * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
  15.  * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
  16.  */
  17. import java.applet.Applet;
  18. import java.awt.*;
  19. import java.io.*;
  20. import java.net.*;
  21. import java.util.*;
  22.  
  23. public class TalkClientApplet extends Applet implements Runnable {
  24.     Socket socket;
  25.     DataOutputStream os;
  26.     DataInputStream is;
  27.     TextField portField, message;
  28.     TextArea display;
  29.     Button button;
  30.     int dataPort;
  31.     boolean trysted;
  32.     Thread receiveThread;
  33.     String host;
  34.     boolean DEBUG = false;
  35.  
  36.     public void init() {
  37.         //Get the address of the host we came from.
  38.         host = getCodeBase().getHost();
  39.  
  40.         //Set up the UI.
  41.         GridBagLayout gridBag = new GridBagLayout();
  42.         GridBagConstraints c = new GridBagConstraints();
  43.         setLayout(gridBag);
  44.  
  45.         message = new TextField("");
  46.         c.fill = GridBagConstraints.HORIZONTAL;
  47.         c.gridwidth = GridBagConstraints.REMAINDER;
  48.         gridBag.setConstraints(message, c); 
  49.         add(message);
  50.  
  51.         display = new TextArea(10, 40);
  52.         display.setEditable(false);
  53.         c.weightx = 1.0;
  54.         c.weighty = 1.0;
  55.         c.fill = GridBagConstraints.BOTH;
  56.         gridBag.setConstraints(display, c); 
  57.         add(display);
  58.  
  59.         Label l = new Label("Enter the port (on host " + host
  60.                             + ") to send the request to:", 
  61.                             Label.RIGHT);
  62.         c.fill = GridBagConstraints.HORIZONTAL;
  63.         c.gridwidth = 1;
  64.         c.weightx = 0.0;
  65.         c.weighty = 0.0;
  66.         gridBag.setConstraints(l, c); 
  67.         add(l);
  68.  
  69.         portField = new TextField(6);
  70.         c.fill = GridBagConstraints.NONE;
  71.         gridBag.setConstraints(portField, c); 
  72.         add(portField);
  73.  
  74.         button = new Button("Connect");
  75.         gridBag.setConstraints(button, c); 
  76.         add(button);
  77.  
  78.         validate();
  79.     }
  80.  
  81.     public synchronized void start() {
  82.         if (DEBUG) {
  83.             System.out.println("In start() method.");
  84.         }
  85.         if (receiveThread == null) {
  86.             trysted = false;
  87.             portField.setEditable(true);
  88.             button.enable();
  89.             os = null;
  90.             is = null;
  91.             socket = null;
  92.             receiveThread = new Thread(this);
  93.             receiveThread.start();
  94.             if (DEBUG) {
  95.                 System.out.println("  Just set everything to null and started thread.");
  96.             }
  97.         } else if (DEBUG) {
  98.             System.out.println("  receiveThread not null! Did nothing!");
  99.         }
  100.     }
  101.  
  102.     public synchronized void stop() {
  103.         if (DEBUG) {
  104.             System.out.println("In stop() method.");
  105.         }
  106.         receiveThread = null;
  107.         trysted = false;
  108.         portField.setEditable(true);
  109.         button.enable();
  110.         notify();
  111.  
  112.         try { //Close input stream.
  113.             if (is != null) {
  114.                 is.close();
  115.                 is = null;
  116.             }
  117.         } catch (Exception e) {} //Ignore exceptions.
  118.  
  119.         try { //Close output stream.
  120.             if (os != null) {
  121.                 os.close();
  122.                 os = null;
  123.             }
  124.         } catch (Exception e) {} //Ignore exceptions.
  125.  
  126.         try { //Close socket.
  127.             if (socket != null) {
  128.                 socket.close();
  129.                 socket = null;
  130.             }
  131.         } catch (Exception e) {} //Ignore exceptions.
  132.     }
  133.             
  134.     public Insets insets() {
  135.         return new Insets(4,4,5,5);
  136.     }
  137.  
  138.     public void paint(Graphics g) {
  139.         Dimension d = size();
  140.         Color bg = getBackground();
  141.  
  142.         g.setColor(bg);
  143.         g.draw3DRect(0, 0, d.width - 1, d.height - 1, true);
  144.         g.draw3DRect(3, 3, d.width - 7, d.height - 7, false);
  145.     }
  146.  
  147.     public synchronized boolean action(Event event, Object arg) {
  148.         int port;
  149.         
  150.         if (DEBUG) {
  151.             System.out.println("In action() method.");
  152.         }
  153.  
  154.         if (receiveThread == null) {
  155.             start();
  156.         }
  157.  
  158.         if (!trysted) {
  159.         //We need to attempt a rendezvous.
  160.  
  161.             if (DEBUG) {
  162.                 System.out.println("  trysted = false. "
  163.                                    + "About to attempt a rendezvous.");
  164.             }
  165.  
  166.             //Get the port the user entered...
  167.             try {
  168.                 port = Integer.parseInt(portField.getText());
  169.             } catch (NumberFormatException e) {
  170.                 //No integer entered. 
  171.                 display.appendText("Please enter an integer below.\n");
  172.                 return true;
  173.             }
  174.             //...and rendezvous with it.
  175.             rendezvous(port);
  176.  
  177.         } else { //We've already rendezvoused. Just send data over.
  178.             if (DEBUG) {
  179.                 System.out.println("  trysted = true. "
  180.                                    + "About to send data.");
  181.             }
  182.             String str = message.getText();
  183.             message.selectAll();
  184.  
  185.             try {
  186.                 os.writeUTF(str);
  187.                 os.flush();
  188.             } catch (IOException e) {
  189.                 display.appendText("ERROR: Applet couldn't write to socket.\n");
  190.                 display.appendText("...Disconnecting.\n");
  191.                 stop();
  192.                 return true;
  193.             } catch (NullPointerException e) {
  194.                 display.appendText("ERROR: No output stream!\n");
  195.                 display.appendText("...Disconnecting.\n");
  196.                 stop();
  197.                 return true;
  198.             }
  199.             display.appendText("Sent: " + str + "\n");
  200.         }
  201.         return true;
  202.     }
  203.  
  204.     synchronized void waitForTryst() {
  205.         //Wait for notify() call from action().
  206.         try {
  207.             wait();        
  208.         } catch (InterruptedException e) {}
  209.  
  210.         if (DEBUG) {
  211.             System.out.println("waitForTryst about to return. "
  212.                                + "trysted = " + trysted + ".");
  213.         }
  214.  
  215.         return;
  216.     }
  217.  
  218.     public void run() {
  219.         String received = null;
  220.  
  221.         waitForTryst();
  222.  
  223.         //OK, now we can send messages.
  224.         while (Thread.currentThread() == receiveThread) {
  225.             try { 
  226.                 //Wait for data from the server.
  227.                 received = is.readUTF();
  228.  
  229.                 //Display it.
  230.                 if (received != null) {
  231.                     display.appendText("Received: " + received + "\n");
  232.                 } else { //success but no data...
  233.                     System.err.println("readUTF() returned no data");
  234.                 }
  235.             } catch (EOFException e) { //Stream has no more data.
  236.                 display.appendText("NOTE: Other applet is disconnected.\n");
  237.                 //display.appendText("...Disconnecting.\n");
  238.                 //stop();
  239.                 return;
  240.             } catch (NullPointerException e) { //Stream doesn't exist.
  241.                 display.appendText("NOTE: Disconnected from server.\n");
  242.                 display.appendText("...Completing disconnect.\n");
  243.                 stop();
  244.                 return;
  245.             } catch (IOException e) { //Perhaps a temporary problem?
  246.                 display.appendText("NOTE: Couldn't read from socket.\n");
  247.                 //display.appendText("...Disconnecting.\n");
  248.                 //stop();
  249.                 return;
  250.             } catch (Exception e) { //Unknown error. Throw tantrum.
  251.                 display.appendText("ERROR: Couldn't read from socket.\n");
  252.                 display.appendText("...Disconnecting.\n");
  253.                 System.err.println("Couldn't read from socket.");
  254.                 e.printStackTrace();
  255.                 stop();
  256.                 return;
  257.             }
  258.         }
  259.     }
  260.  
  261.     private void rendezvous(int port) {
  262.         //Try to open a socket to the port.
  263.         try {
  264.             socket = new Socket(host, port);
  265.         } catch (UnknownHostException e) {
  266.             display.appendText("ERROR: Can't find host: " + host + ".\n");
  267.             return;
  268.         } catch (IOException e) {
  269.             display.appendText("ERROR: Can't open socket on rendezvous port "
  270.                                    + port + " (on host " + host + ").\n");
  271.             return;
  272.         }
  273.  
  274.         //Try to open streams to read and write from the socket.
  275.         try {
  276.             os = new DataOutputStream(socket.getOutputStream());
  277.             is = new DataInputStream(socket.getInputStream());
  278.         } catch (IOException e) {
  279.             display.appendText("ERROR: Created data socket but can't "
  280.                                + "open stream on it.\n");
  281.             display.appendText("...Disconnecting.\n");
  282.             stop();
  283.             return;
  284.         }   
  285.  
  286.         if ((os != null) & (is != null)) {
  287.             if (DEBUG) {
  288.                 System.out.println("Successful rendezvous.");
  289.                 System.out.println("socket = " + socket);
  290.                 System.out.println("output stream = " + os);
  291.                 System.out.println("input stream = " + is);
  292.             }
  293.             //Let the main applet thread know we've successfully rendezvoused.
  294.             portField.setEditable(false);
  295.             button.disable();
  296.             trysted = true;
  297.             notify();
  298.         } else {
  299.             display.appendText("ERROR: Port is valid but communication failed. "
  300.                                    + "Please TRY AGAIN.\n");
  301.         }
  302.     }
  303.  
  304. }
  305.